/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lonnesol.swing.button;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author hualun-alan
 */
public class TriangleIconButton extends IconButton {

    protected int triandleWidth = 5;
    protected int triandleHeight = 10;

    public TriangleIconButton() {
        this("");
    }

    public TriangleIconButton(String text) {
        super(text);
    }

    @Override
    protected void calculateSize() {
        Dimension d = new Dimension(fm.stringWidth(getText()) + HORIZONTAL_OFFSET * 2 + 5 + triandleWidth, fm.getHeight() + VERTICAL_OFFSET * 2);
        setPreferredSize(d);
        setMaximumSize(d);
        setMinimumSize(d);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        drawTriangle(g);
    }

    private void drawTriangle(Graphics g) {
        Graphics2D gd = (Graphics2D) g;

        if (model.isEnabled()) {
            gd.setColor(Color.DARK_GRAY);
        } else {
            gd.setColor(Color.GRAY);
        }

        int startX = getWidth() - 3 - triandleWidth;
        int startY = (getHeight() - triandleHeight) / 2 - 1;

        int[] xPoints = new int[3];
        xPoints[0] = startX;
        xPoints[1] = startX;
        xPoints[2] = startX + 5;
        int[] yPoints = new int[3];
        yPoints[0] = startY;
        yPoints[1] = startY + triandleHeight;
        yPoints[2] = startY + triandleHeight / 2;

        gd.fillPolygon(xPoints, yPoints, 3);

    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame("Button Test");
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel jPanel = new JPanel();
        final IconButton btnView = new TriangleIconButton("View");
        btnView.setEnabled(false);
        IconButton btnEdit = new TriangleIconButton("Edit");
        btnEdit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.out.println("===============");
                btnView.setEnabled(!btnView.isEnabled());
                btnView.setText(btnView.isEnabled() ? "View" : "Test View");
            }
        });

        jPanel.add(btnEdit);
        jPanel.add(btnView);
        jPanel.add(new TriangleIconButton("Approve"));
        jPanel.add(new TriangleIconButton("Reject"));
        jPanel.add(new TriangleIconButton("Un-share"));
        jFrame.getContentPane().add(jPanel);
        jFrame.setSize(500, 500);
        jFrame.setLocationRelativeTo(null);
        jFrame.setVisible(true);
    }
}
